package install.ren.exercise.test.netty;


import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * RPC 编码器
 *
 * @author wanglin/netboy
 * @since 1.0.0
 */
public class MessageEncoder extends MessageToByteEncoder<Message> {
    Logger log = LoggerFactory.getLogger(MessageEncoder.class);

    @Override
    protected void encode(ChannelHandlerContext ctx, Message msg, ByteBuf out) throws Exception {
        if (ctx == null) {
            throw new IllegalArgumentException("channelhandlercontext is null");
        }

        if (msg == null) {
            log.error("data is null");
        }

        if (out == null) {
            throw new IllegalArgumentException("buffer is null");
        }

        //do write
        long len = msg.getLength();
        if (len > 0) {
            log.debug("sgip write msg:{}", msg.toString());
            out.writeBytes(msg.toBytes());
        }
    }
}
